import React, { useState, useEffect } from 'react';
import { Card, List, Avatar, Tag, Typography, Divider, Spin, message, Input, FloatButton, Modal, Form, Dropdown, Menu } from 'antd';
import { SearchOutlined, PlusOutlined, MoreOutlined, DeleteOutlined } from '@ant-design/icons';
import axios from 'axios';

const { Title, Paragraph } = Typography;
const { Search } = Input;

const PluginListPage = () => {
  const [plugins, setPlugins] = useState([]);
  const [filteredPlugins, setFilteredPlugins] = useState([]);
  const [loading, setLoading] = useState(true);
  const [searchText, setSearchText] = useState('');
  const [modalVisible, setModalVisible] = useState(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [selectedPlugin, setSelectedPlugin] = useState(null);
  const [form] = Form.useForm();

  useEffect(() => {
    const fetchPlugins = async () => {
      try {
        setLoading(true);
        // 从公共目录加载plugins.json文件
        const response = await axios.get('/data/plugins.json');
        console.log('插件数据:', response.data);
        setPlugins(response.data);
        setFilteredPlugins(response.data);
      } catch (error) {
        console.error('加载插件列表失败:', error);
        message.error('加载插件列表失败');
      } finally {
        setLoading(false);
      }
    };

    fetchPlugins();
  }, []);

  // 处理搜索
  const handleSearch = (value) => {
    setSearchText(value);
    
    if (!value.trim()) {
      setFilteredPlugins(plugins);
      return;
    }
    
    const searchLower = value.toLowerCase();
    const filtered = plugins.filter(plugin => 
      plugin.name.toLowerCase().includes(searchLower) || 
      plugin.type.toLowerCase().includes(searchLower) || 
      plugin.description.toLowerCase().includes(searchLower) ||
      plugin.nickname.toLowerCase().includes(searchLower)
    );
    
    setFilteredPlugins(filtered);
  };

  // 处理Modal确定按钮点击
  const handleModalOk = () => {
    form.validateFields().then(values => {
      console.log('创作插件数据:', values);
      message.success('插件创作成功');
      form.resetFields();
      setModalVisible(false);
    }).catch(errorInfo => {
      console.log('表单验证失败:', errorInfo);
    });
  };

  // 处理Modal取消按钮点击
  const handleModalCancel = () => {
    form.resetFields();
    setModalVisible(false);
  };

  // 显示创作插件Modal
  const showCreateModal = () => {
    setModalVisible(true);
  };

  // 根据插件类型获取不同的颜色
  const getTagColor = (type) => {
    const colorMap = {
      '抖音': 'magenta',
      '王者荣耀': 'green',
      // 可以根据需要添加更多类型的颜色
    };
    
    return colorMap[type] || 'blue';
  };

  // 处理删除菜单点击
  const handleMenuClick = (plugin) => {
    setSelectedPlugin(plugin);
    setDeleteModalVisible(true);
  };

  // 确认删除插件
  const confirmDelete = () => {
    // 从列表中移除该插件
    const updatedPlugins = plugins.filter(item => item.id !== selectedPlugin.id);
    setPlugins(updatedPlugins);
    
    // 如果当前有搜索结果，也需要更新过滤后的列表
    if (searchText) {
      const updatedFilteredPlugins = filteredPlugins.filter(item => item.id !== selectedPlugin.id);
      setFilteredPlugins(updatedFilteredPlugins);
    }
    
    message.success('插件已删除');
    setDeleteModalVisible(false);
  };

  // 渲染下拉菜单
  const getDropdownMenu = (plugin) => {
    const items = [
      {
        key: 'delete',
        icon: <DeleteOutlined />,
        label: '删除',
        onClick: () => handleMenuClick(plugin)
      }
    ];
    
    return { items };
  };

  return (
    <>
      <Card bordered={false} bodyStyle={{ padding: '24px' }}>
        <div style={{ marginBottom: '34px', display: 'flex', justifyContent: 'center' }}>
          <Search
            placeholder="搜索插件名称、类型、描述..."
            allowClear
            enterButton={<SearchOutlined />}
            size="large"
            onSearch={handleSearch}
            onChange={(e) => handleSearch(e.target.value)}
            style={{ width: '100%', maxWidth: '800px' }}
          />
        </div>
        
        {loading ? (
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <Spin size="large" />
          </div>
        ) : filteredPlugins.length > 0 ? (
          <List
            grid={{ 
              gutter: 24, 
              xs: 1, 
              sm: 2, 
              md: 3, 
              lg: 3, 
              xl: 4, 
              xxl: 4 
            }}
            dataSource={filteredPlugins}
            renderItem={plugin => (
              <List.Item>
                <Card
                  hoverable
                  style={{ borderRadius: '8px', height: '100%' }}
                >
                  <div style={{ marginBottom: '12px', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                    <Tag color={getTagColor(plugin.type)}>
                      {plugin.type}
                    </Tag>
                    <Dropdown menu={getDropdownMenu(plugin)} trigger={['click']} placement="bottomRight">
                      <MoreOutlined style={{ fontSize: '18px', cursor: 'pointer' }} />
                    </Dropdown>
                  </div>
                  <Title level={4} style={{ marginTop: '0' }}>{plugin.name}</Title>
                  <Paragraph type="secondary" style={{ height: '40px', overflow: 'hidden' }}>
                    {plugin.description}
                  </Paragraph>
                  <Divider style={{ margin: '12px 0' }} />
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <Avatar size="small" src={plugin.avatar} style={{ marginRight: '8px' }} />
                    <span>{plugin.nickname}</span>
                  </div>
                </Card>
              </List.Item>
            )}
          />
        ) : (
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            {searchText ? (
              <Typography.Text type="secondary">未找到匹配的插件</Typography.Text>
            ) : (
              <Typography.Text type="secondary">暂无插件数据</Typography.Text>
            )}
          </div>
        )}
      </Card>
      
      {/* 悬浮加号按钮 */}
      <FloatButton 
        icon={<PlusOutlined />} 
        type="primary"
        tooltip="创作插件"
        style={{ 
          width: '56px', 
          height: '56px', 
          right: '30px', 
          bottom: '30px' 
        }}
        onClick={showCreateModal}
      />

      {/* 创作插件Modal */}
      <Modal
        title="我要创作"
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
        centered
        bodyStyle={{ padding: '10px 0' }}
      >
        <Form
          form={form}
          layout="vertical"
          name="createPluginForm"
        >
          <Form.Item
            name="type"
            label={<span style={{ fontWeight: 'bold' }}>插件类型</span>}
            rules={[{ required: true, message: '请输入插件类型' }]}
          >
            <Input 
              placeholder="如：抖音、王者荣耀等" 
              style={{ marginTop: 8 }}
            />
          </Form.Item>
          <Form.Item
            name="name"
            label={<span style={{ fontWeight: 'bold' }}>插件名称</span>}
            rules={[{ required: true, message: '请输入插件名称' }]}
          >
            <Input 
              placeholder="请输入插件名称" 
              style={{ marginTop: 8 }}
            />
          </Form.Item>
        </Form>
      </Modal>
      
      {/* 删除确认对话框 */}
      <Modal
        title="确认删除"
        open={deleteModalVisible}
        onOk={confirmDelete}
        onCancel={() => setDeleteModalVisible(false)}
        okText="确认"
        cancelText="取消"
        okButtonProps={{ danger: true }}
      >
        <p>确认要删除该插件吗？</p>
      </Modal>
    </>
  );
};

export default PluginListPage; 